package com.choosefine.it.base;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.dto.PushDTO;
import com.choosefine.it.common.json.JsonUtil;
import com.choosefine.it.common.utils.Assert;
import com.choosefine.it.common.utils.URLHandlerUtils;


/**
 * @author 潘钱钦
	2017下午6:38:40
 */
@Service("sendPush")
public class SendPush extends BaseService{
	/** 推送-pushService **/

	@Value("#{yaml.get('pushService.jpush')}")
	final String					PUSH_URL		= null;

	@Autowired
	RestTemplate restTempLate;
	
	@Autowired
	RedisTemplate<String, String>	redisTemplate;
	
	public  void sendPushByUsername(String userName, String pushType, String content) {
		PushDTO push = getPushObj(userName, pushType, content);
		ResponseEntity<Map> result = restTempLate.exchange(URLHandlerUtils.getUrlBuffer(pushURL,PUSH_URL).toString()
				, HttpMethod.POST, new HttpEntity<>(push),
				Map.class);
		// 对返回的result做校验
		boolean resultBool = null != result && result.getBody().get("status").toString().equals("200");
		Assert.assertEqu(resultBool, CommonConstant.MSG_PUSH_ERR);
	}

	/**
	 * 设置推送内容
	 * @param username 用户名
	 * @param pushType 推送类型
	 * @param content 推送内容
	 * @return
	 */
	public  PushDTO getPushObj(String username, String pushType, String content) {
		PushDTO push = new PushDTO();
		// 发送推送通知用户修改
		String rid = redisTemplate.opsForValue().get(username);
		Map<String, Object> contentMap = new HashMap<>();

		contentMap.put("username", username);
		contentMap.put("msgContent", content);
		push.setAudience("alias:" + rid);
		push.setMessageTitle(content);
		push.setNotification(content);
		push.setMessageContentType(pushType);
		push.setMessageContent(JsonUtil.toJson(contentMap));
		return push;
	}
}
